#!/bin/bash

# get current IP of SDK container
IP=$(hostname -I | cut -d " " -f1 -s)

BASE_FOLDER="/workspace/images"

if [ ! -f "${BASE_FOLDER}/berrymill.template" ]; then
    # copy the default template
    cp /etc/berrymill/berrymill_local.conf ${BASE_FOLDER}/berrymill.template
fi

if [ -f "${BASE_FOLDER}" ]; then
    # if already a berrymill config exists
    cat ${BASE_FOLDER}/berrymill.conf | grep "${IP}"
    if [ $? -ne 0 ]; then
        # and the config doesn't contain the local IP
        # backup the config
        mv ${BASE_FOLDER}/berrymill.conf ${BASE_FOLDER}/berrymill_$(date +%s).old
        # and add the right config
        cp ${BASE_FOLDER}/berrymill.template ${BASE_FOLDER}/berrymill.conf
        sed -i "s/CONTAINERIP/${IP}/g" ${BASE_FOLDER}/berrymill.conf
    fi
else
    # genrate a berrymill config
    cp ${BASE_FOLDER}/berrymill.template ${BASE_FOLDER}/berrymill.conf
    sed -i "s/CONTAINERIP/${IP}/g" ${BASE_FOLDER}/berrymill.conf
fi
